/*
 * DA2.cpp
 *
 * Created: 2/28/2014 2:03:40 PM
 *  Author: Jared
 * 
 *	Assignment to create a counter that counts from 0 to 255 with a 0.25s delay (50% duty cycle, 0.5 sec period)
 * and track every 10 counts with a 9th LED on the falling edge.  Also use an interrupt to catch every second
 * falling edge of the 9th LED pin.
 */ 


#include <avr/io.h>
#include <avr/interrupt.h>

void Delay(void);

int main(void)
{
		DDRB = 0xFF;						// Enable ports B, C and D
		DDRC = 0xFF;
		DDRD = 0x00;
		
		PORTB = 0x01;
		PORTC = 0x00;
		EIMSK = 0x01;						// enable int0 (PD2)
		EICRA = 0x02;						 // trigger on falling edge
		sei();								 // enable interrupt
		
		
		while(TCNT0 < 256){					// count/loop up to 256
			Delay ();						// call delay subroutine
			TCNT0 ++;						// increment counter
			PORTB = TCNT0;					// output counter to PortB
			if ((TCNT0 % 10) == 0){			// if counter is divisible by 10
				PORTC ^= (1<<0);			// toggle PC0 for the 9th LED
				PORTC ^= 100;				 // set PC2 = PC0 to save power
			}
		}
		return 0;	
}

void Delay(void)
{
		TCNT1 = 0x85EE;						// TCNT = 2^n - x/s = 2^8 - (0.25sec delay * 8MHz)/64
		TCCR1A = 0x00;						//
		TCCR1B = 0x03;						// CS02 = 0, CS01 = 1, CS00 = 0,  0b011 = 3
		while((TIFR1&0x01) == 0){			// While TOV1 is not set
			//wait
		}
		TIFR1 = 0x01;						
		return;
}

ISR(INT0_vect){								// delay subroutine
		TCNT2 ++;
		while (TCNT2 = 0x02){				// trigger on falling edge
			PORTC ^= (1<<1);				// toggle PC1 connected to PD2 for interrupt
			TCNT2 = 0x00;
		}
}